package com.kuang.springcloud.controller;

import com.kuang.springcloud.pojo.Dept;
import com.kuang.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: springcloud
 * @description: 提供restful服务
 * @author: 陈恩涛
 * @create: 2020-12-15 10:23
 **/

@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet",commandProperties = { //失败回调函数为hystixGet
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),// 是否开启熔断策略。默认值为true
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value ="10"), //10ms内，请求并发数超出则触发熔断策略。默认值为20
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000"),//当熔断策略开启后，延迟多久尝试再次请求远程服务。默认为5秒。
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "60")//10ms内，出现错误的请求百分比达到限制，则触发熔断策略。默认为50%
    })
    public Dept get(@PathVariable("id") long id){
        Dept dept = deptService.queryById(id);

        if (dept == null) {
            throw new RuntimeException("id=>"+id+",不存在该部门,或者信息无法找到");
        }
        return dept;
    }

    //备选方案
    private Dept hystrixGet(@PathVariable("id") long id){
        return new Dept()
                .setDeptno(id)
                .setDname("id=>"+id+",对应的信息为null--@Hystrix")
                .setDb_source("no this database in mysql!");
    }

}
